﻿using System;
using System.Collections.Specialized;
using System.Net;
using NetActive.Notifications.Services.WP7.Interfaces;

namespace NetActive.Notifications.Services.WP7
{
    /// <summary>
    /// Class representing a notification response from Microsoft's Notification Services.
    /// </summary>
    public class NotificationResponse
    {
        /// <summary>
        /// Gets the notification this response is for.
        /// </summary>
        public INotification Notification { get; internal set; }

        /// <summary>
        /// Gets the date/time the notification was sent.
        /// </summary>
        public DateTime NotificationSentAtUtc { get; internal set; }

        /// <summary>
        /// Gets the date/time this response was received.
        /// </summary>
        public DateTime ResponseReceivedAtUtc { get; internal set; }

        /// <summary>
        /// Gets the client device status as returned by the Push Notification Services.
        /// </summary>
        public string Status { get; internal set; }

        /// <summary>
        /// Gets the device channel status as returned by the Push Notification Services.
        /// </summary>
        public string ChannelStatus { get; internal set; }

        /// <summary>
        /// Gets the device connection status as returned by the Push Notification Services.
        /// </summary>
        public string DeviceConnectionStatus { get; internal set; }

        /// <summary>
        /// Gets the actual error occurred, if any.
        /// </summary>
        public Exception Error { get; internal set; }

        #region Internal Helper Methods

        internal void ApplyWebResponse(WebResponse webResponse)
        {
            ResponseReceivedAtUtc = DateTime.UtcNow;
            ApplyResponseHeaders(webResponse.Headers);
        }

        internal void ApplyWebException(WebException webException)
        {
            ResponseReceivedAtUtc = DateTime.UtcNow;
            Error = webException; 
            ApplyResponseHeaders(webException.Response.Headers);
        }

        internal void ApplyException(Exception exception)
        {
            ResponseReceivedAtUtc = DateTime.UtcNow;
            Error = exception;
        }

        internal void ApplyResponseHeaders(NameValueCollection headers)
        {
            Status = headers["X-NotificationStatus"] ?? string.Empty;
            ChannelStatus = headers["X-SubscriptionStatus"] ?? string.Empty;
            DeviceConnectionStatus = headers["X-DeviceConnectionStatus"] ?? string.Empty;
        }

        #endregion
    }
}